<template>
  <div class="p-2">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
        <el-form-item label="医院名称" prop="hospitalName">
          <el-input
            v-model="queryParams.hospitalName"
            placeholder="请输入医院名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="合作状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择合作状态" clearable style="width: 200px">
            <el-option v-for="dict in beauty_hospital_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="结算方式" prop="settlementType">
          <el-select v-model="queryParams.settlementType" placeholder="请选择结算方式" clearable style="width: 200px">
            <el-option v-for="dict in beauty_settlement_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 工具栏 -->
      <el-row :gutter="10" class="mb-4">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['beauty:hospital:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['beauty:hospital:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['beauty:hospital:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['beauty:hospital:export']"
          >导出</el-button>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="hospitalList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
<!--        <el-table-column label="医院ID" align="center" prop="hospitalId" width="100" />-->
        <el-table-column label="医院名称" align="center" prop="hospitalName" width="200" show-overflow-tooltip />
        <el-table-column label="联系人" align="center" prop="contactPerson" width="100" />
        <el-table-column label="联系电话" align="center" prop="phone" width="120" />
        <el-table-column label="医院地址" align="center" prop="address" show-overflow-tooltip />
        <el-table-column label="结算方式" align="center" prop="settlementType" width="100">
          <template #default="scope">
            <dict-tag :options="beauty_settlement_type" :value="scope.row.settlementType" />
          </template>
        </el-table-column>
        <el-table-column label="合作状态" align="center" prop="status" width="100">
          <template #default="scope">
            <dict-tag :options="beauty_hospital_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="操作" align="center" fixed="right" width="250">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="View"
              @click="handleDetail(scope.row)"
              v-hasPermi="['beauty:hospital:query']"
            >详情</el-button>
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['beauty:hospital:edit']"
            >修改</el-button>
            <el-button
              v-if="scope.row.status !== '1'"
              link
              type="success"
              @click="handleEnable(scope.row)"
              v-hasPermi="['beauty:hospital:edit']"
            >启用</el-button>
            <el-button
              v-else
              link
              type="warning"
              @click="handleDisable(scope.row)"
              v-hasPermi="['beauty:hospital:edit']"
            >停用</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
      <el-form ref="hospitalFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="医院名称" prop="hospitalName">
              <el-input v-model="form.hospitalName" placeholder="请输入医院名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算方式" prop="settlementType">
              <el-select v-model="form.settlementType" placeholder="请选择结算方式" style="width: 100%">
                <el-option v-for="dict in beauty_settlement_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="医院地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入医院地址" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合作状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in beauty_hospital_status" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="医院简介" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入医院简介" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="医院详情" v-model="detailDialog.visible" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="医院ID">{{ detailDialog.data.hospitalId }}</el-descriptions-item>
        <el-descriptions-item label="医院名称">{{ detailDialog.data.hospitalName }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ detailDialog.data.contactPerson }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailDialog.data.phone }}</el-descriptions-item>
        <el-descriptions-item label="医院地址" :span="2">{{ detailDialog.data.address }}</el-descriptions-item>
        <el-descriptions-item label="结算方式">
          <dict-tag :options="beauty_settlement_type" :value="detailDialog.data.settlementType" />
        </el-descriptions-item>
        <el-descriptions-item label="合作状态">
          <dict-tag :options="beauty_hospital_status" :value="detailDialog.data.status" />
        </el-descriptions-item>
        <el-descriptions-item label="医院简介" :span="2">{{ detailDialog.data.description }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailDialog.data.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailDialog.data.updateTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="BeautyHospital">
import { ref, reactive, getCurrentInstance } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import { ElForm, ElMessageBox, ElMessage } from 'element-plus';
import { listHospital, getHospital, addHospital, updateHospital, delHospital, enableHospital, disableHospital } from '@/api/beauty/hospital';
import type { HospitalQuery, HospitalVO, HospitalForm } from '@/api/beauty/hospital';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { beauty_hospital_status, beauty_settlement_type } = toRefs<any>(proxy?.useDict('beauty_hospital_status', 'beauty_settlement_type'));

const loading = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const hospitalList = ref<HospitalVO[]>([]);

const queryFormRef = ref<InstanceType<typeof ElForm>>();
const hospitalFormRef = ref<InstanceType<typeof ElForm>>();

const queryParams = ref<HospitalQuery>({
  pageNum: 1,
  pageSize: 10,
  hospitalName: undefined,
  status: undefined,
  settlementType: undefined
});

const dialog = reactive({
  visible: false,
  title: ''
});

const detailDialog = reactive({
  visible: false,
  data: {} as HospitalVO
});

const form = ref<HospitalForm>({
  hospitalName: '',
  contactPerson: '',
  phone: '',
  address: '',
  settlementType: '2',
  status: '0',
  description: ''
});

const rules = reactive({
  hospitalName: [
    { required: true, message: '医院名称不能为空', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '联系人不能为空', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '联系电话不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  settlementType: [
    { required: true, message: '结算方式不能为空', trigger: 'change' }
  ]
});

// 查询医院列表
function getList() {
  loading.value = true;
  listHospital(queryParams.value).then((response: any) => {
    hospitalList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection: HospitalVO[]) {
  ids.value = selection.map(item => item.hospitalId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 新增按钮操作
function handleAdd() {
  reset();
  dialog.visible = true;
  dialog.title = '添加医院';
}

// 修改按钮操作
function handleUpdate(row?: HospitalVO) {
  reset();
  const hospitalId = row?.hospitalId || ids.value[0];
  getHospital(hospitalId).then((response: any) => {
    form.value = response.data;
    dialog.visible = true;
    dialog.title = '修改医院';
  });
}

// 详情按钮操作
function handleDetail(row: HospitalVO) {
  getHospital(row.hospitalId).then((response: any) => {
    detailDialog.data = response.data;
    detailDialog.visible = true;
  });
}

// 提交按钮
function submitForm() {
  hospitalFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.hospitalId) {
        updateHospital(form.value).then(() => {
          ElMessage.success('修改成功');
          dialog.visible = false;
          getList();
        });
      } else {
        addHospital(form.value).then(() => {
          ElMessage.success('新增成功');
          dialog.visible = false;
          getList();
        });
      }
    }
  });
}

// 取消按钮
function cancel() {
  dialog.visible = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    hospitalName: '',
    contactPerson: '',
    phone: '',
    address: '',
    settlementType: '2',
    status: '0',
    description: ''
  };
  hospitalFormRef.value?.resetFields();
}

// 删除按钮操作
function handleDelete(row?: HospitalVO) {
  const hospitalIds = row?.hospitalId ? [row.hospitalId] : ids.value;
  ElMessageBox.confirm('是否确认删除医院编号为"' + hospitalIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return delHospital(hospitalIds);
  }).then(() => {
    getList();
    ElMessage.success('删除成功');
  });
}

// 启用医院
function handleEnable(row: HospitalVO) {
  ElMessageBox.confirm('确认要启用医院"' + row.hospitalName + '"吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    return enableHospital(row.hospitalId);
  }).then(() => {
    getList();
    ElMessage.success('启用成功');
  });
}

// 停用医院
function handleDisable(row: HospitalVO) {
  ElMessageBox.confirm('确认要停用医院"' + row.hospitalName + '"吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return disableHospital(row.hospitalId);
  }).then(() => {
    getList();
    ElMessage.success('停用成功');
  });
}

// 导出按钮操作
function handleExport() {
  ElMessageBox.confirm('是否确认导出所有医院数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // TODO: 实现导出功能
    ElMessage.success('导出成功');
  });
}

getList();
</script>
